#!/usr/bin/env python

import pyxmppclient
import sys
import logging
import locale
import codecs
import gootalk
import traceback

if (__name__ == '__main__'):
    
    # XMPP protocol is Unicode-based to properly display data received
    # _must_ convert it to local encoding or UnicodeException may be raised
    locale.setlocale(locale.LC_CTYPE, "")
    encoding = locale.getlocale()[1]
    if not encoding:
        encoding = "us-ascii"
    sys.stdout = codecs.getwriter(encoding)(sys.stdout, errors = "replace")
    sys.stderr = codecs.getwriter(encoding)(sys.stderr, errors = "replace")

    # PyXMPP uses `logging` module for its debug output
    # applications should set it up as needed
    logger = logging.getLogger()
    logger.addHandler(logging.StreamHandler())
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    logfile = logging.FileHandler('ggotalk.log')
    logfile.setFormatter(formatter)
    logger.addHandler(logfile)
    logger.setLevel(logging.INFO) # change to DEBUG for higher verbosity
    
    if (len(sys.argv) < 5):
        logging.info('Usage: python pyxmppchat.py node domain resource password')
    node = sys.argv[1]
    domain = sys.argv[2]
    resource = sys.argv[3]
    password = sys.argv[4]
    
    gootalk.jid = '%s@%s' % (node, domain)

    pyxmppclient.clientInstance = pyxmppclient.PyJabberClient(node, domain, resource, password)
    logging.info('connecting...')

    while (True):

        connectret = pyxmppclient.clientInstance.connect()
        logging.info('connected looping... %s' % (connectret))
        try:
            pyxmppclient.clientInstance.loop(1)
        except KeyboardInterrupt:
            logging.info('disconnecting...')
            pyxmppclient.clientInstance.disconnect()
            pyxmppclient.clientInstance = None
            sys.exit(0)
        except:
            logging.info(traceback.print_exc())

    logging.info('exiting...')

